<template>
	<div>
		<a-form
			:wrapper-col="{ span: 16 }"
			:label-col="{ span: 8 }"
			autocomplete="off"
			labelAlign="right"
			ref="formRef"
			:model="formData"
			:rules="formRules"
		>
			<a-row>
				<a-col :span="12">
					<a-form-item label="采购方式" name="orderMethod">
						<a-select
							:disabled="props.disabled"
							placeholder="请选择采购方式"
							:options="tool.dictList('orderMethod')"
							v-model:value="formData.orderMethod"
						>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="供应商" name="supplierId">
						<xn-page-selector
							:disabled="props.disabled"
							ref="supplierRef"
							:field-names="{ label: 'name', value: 'id' }"
							:page-function="(param) => querySupplierList(param)"
							v-model:value="formData.supplierId"
							placeholder="请选择供应商"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="选择项目" name="proId">
						<xn-page-selector
							:disabled="props.disabled"
							@change="proinfoChange"
							ref="proinfoRef"
							:field-names="{ label: 'name', value: 'id' }"
							:page-function="(param) => proinfo.proinfopage(param)"
							v-model:value="formData.proId"
							placeholder="请选择项目"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="选择合同" name="contractId">
						<a-select
							:disabled="props.disabled"
							:options="contractList"
							:placeholder="formData.proId ? '请选择合同' : '请先选择项目'"
							v-model:value="formData.contractId"
						>
						</a-select>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="付款日期" name="settingTime">
						<a-date-picker
							:disabled="props.disabled"
							format="YYYY-MM-DD"
							valueFormat="YYYY-MM-DD hh:mm:ss"
							style="width: 100%"
							v-model:value="formData.settingTime"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="预计到货日期" name="expectDate">
						<a-date-picker
							:disabled="props.disabled"
							valueFormat="YYYY-MM-DD hh:mm:ss"
							format="YYYY-MM-DD"
							style="width: 100%"
							v-model:value="formData.expectDate"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="采购员" name="orderPerson">
						<div @click="selectionParticipants()">
							<a-input
								readonly
								:disabled="props.disabled"
								v-model:value="formData.orderPerson"
								placeholder="请选择采购员"
								allow-clear
							/>
						</div>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="选择仓库" name="warehouseId">
						<xn-page-selector
							ref="warehouseRef"
							:disabled="props.disabled"
							:field-names="{ label: 'warehouseName', value: 'id' }"
							:page-function="(param) => storeCenterApi.getPage(param)"
							v-model:value="formData.warehouseId"
							placeholder="请选择仓库"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="备注" name="remark">
						<a-input :disabled="props.disabled" v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="24">
					<a-row>
						<a-col v-if="props.disabled">
							<a-button class="childAddButton"> 商品明细 </a-button>
						</a-col>
						<a-col v-else>
							<a-button type="primary" class="childAddButton" @click="addProduct()">
								<PlusOutlined />
								新增
							</a-button>
							<a-popconfirm title="是否删除?" @confirm="removeGoods()">
								<a-button style="margin-left: 12px" type="remove" danger>
									<LineOutlined />
									删除
								</a-button>
							</a-popconfirm>
						</a-col>
					</a-row>
					<a-table
						:row-selection="options.rowSelection"
						:pagination="false"
						:columns="goodsColumns"
						:data-source="formData.purchaseOrderDetailList"
						:scroll="{ x: 1000 }"
					>
						<template #bodyCell="{ index, record, column }">
							<template v-if="column.dataIndex === 'index'">
								<span>{{ index + 1 }}</span>
							</template>

							<template v-if="column.dataIndex === 'price'">
								<a-input
									:disabled="props.disabled"
									@input="priceChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.price"
								/>
							</template>

							<template v-if="column.dataIndex === 'orderNum'">
								<a-input
									:disabled="props.disabled"
									@input="orderNumChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.orderNum"
								/>
							</template>

							<template v-if="column.dataIndex === 'taxRate'">
								<a-input
									:disabled="props.disabled"
									@input="taxRateChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.taxRate"
								/>
							</template>

							<template v-if="column.dataIndex === 'taxPrice'">
								<a-input
									:disabled="props.disabled"
									@input="taxChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.taxPrice"
								/>
							</template>

							<template v-if="column.dataIndex === 'noTaxPrice'">
								<a-input
									:disabled="props.disabled"
									@input="excludingTaxChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.noTaxPrice"
								/>
							</template>

							<template v-if="column.dataIndex === 'deliveryDate'">
								<a-date-picker
									:disabled="props.disabled"
									valueFormat="YYYY-MM-DD hh:mm:ss"
									format="YYYY-MM-DD"
									style="width: 120px"
									v-model:value="record.deliveryDate"
								/>
							</template>

							<template v-if="column.dataIndex === 'remark'">
								<a-input :disabled="props.disabled" :style="{ width: column.width }" v-model:value="record.remark" />
							</template>
						</template>
					</a-table>
				</a-col>
			</a-row>

			<div style="margin-top: 15px">
				<span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
			</div>
			<a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px; margin-left: 20px">
				<a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>采购数量:</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="waresNum" />
				</a-col>
				<!-- <a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>含税总金额</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="taxAmount" />
				</a-col>
				<a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>不含税总金额</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="noTaxAmount" />
				</a-col> -->
			</a-row>
		</a-form>
		<system :value="{}"></system>
		<user-selector-plus
			ref="userSelectorPlusRef"
			:org-tree-api="selectorApiFunction.orgTreeApi"
			:user-page-api="selectorApiFunction.userPageApi"
			:checked-user-list-api="selectorApiFunction.checkedUserListApi"
			:data-is-converter-flw="true"
			@onBack="selectUserCallback"
		/>
		<productSelector
			:data-provider="getOrderDetailList"
			:columns="selectorColumns"
			@onProductChange="onProductChange"
			ref="productsRef"
		/>
	</div>
</template>

<script setup name="dbsForm">
	import { required } from '@/utils/formRules'
	import proinfo from '@/api/pm/pm/index'
	import supplierApi from '@/api/base_data/supplierApi'
	import storeCenterApi from '@/api/base_data/storeCenterApi'
	import { message } from 'ant-design-vue'
	import { toRaw, onMounted } from 'vue'
	import productSelector from '@/components/Selector/productSelector.vue'
	import UserSelectorPlus from '@/components/Selector/userSelectorPlus.vue'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	import orgApi from '@/api/sys/orgApi'
	import contractpurmaterialApi from '@/api/purchasing/order/contractpurmaterialApi'
	import contractbaseApi from '@/api/contract/base/index'
	import tool from '@/utils/tool'
	import system from '@/components/Task/system.vue'

	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })

	const formRef = ref()
	const proinfoRef = ref()
	const productsRef = ref()
	const supplierRef = ref()
	const contractList = ref([])
	const warehouseRef = ref()
	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const waresNum = ref(0)
	const taxAmount = ref(0)
	const noTaxAmount = ref(0)
	const userSelectorPlusRef = ref()
	const selectorApiFunction = {
		orgTreeApi: (param) => {
			return orgApi.orgOrgTreeSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		userPageApi: (param) => {
			return orgApi.orgUserSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		checkedUserListApi: (param) => {
			return userCenterApi.userCenterGetUserListByIdList(param).then((data) => {
				return Promise.resolve(data)
			})
		}
	}
	const selectionParticipants = () => {
		let data = []
		if (formData.value.orderPersonId) {
			data.push({
				key: 'USER',
				label: formData.value.orderPerson,
				value: formData.value.orderPersonId
			})
		}
		userSelectorPlusRef.value.showUserPlusModal(data)
	}

	const selectUserCallback = (value) => {
		formData.value.orderPersonId = value.value
		formData.value.orderPerson = value.label
	}

	const props = defineProps({
		value: {
			type: Object,
			default: () => {}
		},
		disabled: {
			type: Boolean,
			default: () => false
		}
	})
	watch(
		() => props.value,
		(newVal, oldVal) => {
			if (newVal) {
				let formValue = { ...newVal }
				let detailList = formValue.purchaseOrderDetailList.map((it) => {
					it['name'] = it['proMaterial']['name']
					it['brand'] = it['proMaterial']['brand']
					it['spec'] = it['proMaterial']['spec']
					it['code'] = it['proMaterial']['code']
					it['unit'] = it['proMaterial']['unit']
					it['key'] = it['materialId']
					return it
				})
				formValue.purchaseOrderDetailList = detailList
				formData.value = formValue
			}
		},
		{ deep: true, immediate: true }
	)

	onMounted(() => {
		nextTick(() => {
			warehouseRef.value.onPage({})
			proinfoRef.value.onPage({})
			supplierRef.value.onPage({})
		})
	})

	const proinfoChange = (id) => {
		contractbaseApi
			.page({
				proId: id,
				types: '2,5',
				status: 1
			})
			.then((res) => {
				contractList.value = res.records.map((element) => {
					return {
						label: element['name'],
						value: element['id']
					}
				})
			})
			.catch(() => {})
	}

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const addProduct = () => {
		if (!formData.value.contractId) {
			message.error('请选择合同')
			return
		}
		if (!formData.value.purchaseOrderDetailList) {
			formData.value.purchaseOrderDetailList = []
		}
		productsRef.value.showDialog(formData.value.purchaseOrderDetailList)
	}
	const removeGoods = () => {
		let datas = formData.value.purchaseOrderDetailList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['key'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
		waresNum.value = totalOrderNum()
	}
	const selectedRowKeys = ref([])

	const querySupplierList = (params) => {
		return new Promise((resolve, rejected) => {
			supplierApi
				.getPage(params)
				.then((res) => {
					res.records = res.records.map((it) => {
						return {
							id: it.id,
							name: it.supplierEntity == 1 ? it.companyName : it.name
						}
					})
					resolve(res)
				})
				.catch((e) => rejected(e))
		})
	}

	const formatPrice = (text) => {
		let value = text.match(/^\d*(\.?\d{0,2})/g)[0] || null
		if (isNaN(value)) {
			return ''
		}
		return value
	}
	const priceChange = (record) => {
		record.price = formatPrice(record.price)
	}

	const taxRateChange = (record) => {
		record.taxRate = formatPrice(record.taxRate)
	}

	const taxChange = (record) => {
		record.taxPrice = formatPrice(record.taxPrice)
		taxAmount.value = totalTax()
	}

	const excludingTaxChange = (record) => {
		record.noTaxPrice = formatPrice(record.noTaxPrice)
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const orderNumChange = (record) => {
		let value = record.orderNum.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.orderNum = ''
		} else {
			record.orderNum = value
		}
		waresNum.value = totalOrderNum()
	}

	const totalExcludingTaxTax = () => {
		let orderList = formData.value.purchaseOrderDetailList || []
		let amount = 0
		orderList.forEach((it) => {
			let noTaxPrice = it['noTaxPrice']
			if (noTaxPrice) {
				amount += parseFloat(noTaxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}
	const totalTax = () => {
		let orderList = formData.value.purchaseOrderDetailList || []
		let amount = 0
		orderList.forEach((it) => {
			let taxPrice = it['taxPrice']
			if (taxPrice) {
				amount += parseFloat(taxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}

	const totalOrderNum = () => {
		let orderList = formData.value.purchaseOrderDetailList || []
		let amount = 0
		orderList.forEach((it) => {
			let orderNum = it['orderNum']
			if (orderNum) {
				amount += parseInt(orderNum)
			}
		})
		return amount
	}

	// 默认要校验的
	const formRules = {
		orderMethod: [required('请选择采购方式')],
		proId: [required('请选择项目')],
		contractId: [required('请选择合同')],
		warehouseId: [required('请选择仓库')],
		supplierId: [required('请选择供应商')],
		orderPerson: [required('请选择采购员')],
		expectDate: [required('请选择预计到货日期')],
		settingTime: [required('请选择付款日期')]
	}

	// 验证并提交数据
	const getData = () => {
		return new Promise((resolve, reject) => {
			submitApi()
				.then((data) => {
					resolve(data)
				})
				.catch((error) => {
					let msg = error.message
					if (msg) {
						message.error(msg)
					}
				})
		})
	}

	const validatedField = (orderList) => {
		if (orderList.length <= 0) {
			return '请添加商品'
		}
		let msg = null
		let itemRules = [
			{
				field: 'price',
				error: '采购价格不能为空!'
			},
			{
				field: 'orderNum',
				error: '采购数量不能为空!'
			},
			{
				field: 'deliveryDate',
				error: '交货日期不能为空!'
			}
		]
		for (let i = 0; i < orderList.length; i++) {
			for (let rule of itemRules) {
				let item = orderList[i]
				let itemValue = item[rule['field']]
				if (!itemValue) {
					msg = `第${i + 1}行${rule['error']}`
					break
				}
			}
		}
		return msg
	}

	const submitApi = () => {
		return new Promise((resolve, reject) => {
			formRef.value
				.validate()
				.then(() => {
					let orderList = toRaw(formData.value.purchaseOrderDetailList) || []
					let msg = validatedField(orderList)
					if (msg) {
						reject(new Error(msg))
					} else {
						let params = { ...formData.value }
						params.purchaseOrderDetailList = orderList
						params['flowCode'] = 'FLW_PURCHASE_ORDER'
						Object.assign(params, {
							noTaxAmount: noTaxAmount.value,
							taxAmount: taxAmount.value,
							waresNum: waresNum.value
						})
						resolve(params)
					}
				})
				.catch((e) => reject(e))
		})
	}

	// 重置
	const resetForm = () => {
		formRef.value.resetFields()
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		getData,
		resetForm
	})

	const onProductChange = (items) => {
		let purchaseOrderDetailList = formData.value.purchaseOrderDetailList || []
		items.forEach((it) => {
			let find = purchaseOrderDetailList.find((item) => {
				return item['materialId'] == it['materialId']
			})
			if (find) {
				it = Object.assign(it, find)
			}
		})
		formData.value.purchaseOrderDetailList = items
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
		waresNum.value = totalOrderNum()
	}

	const getOrderDetailList = (parameter) => {
		return contractpurmaterialApi
			.getPage(
				Object.assign(parameter, {
					contractId: formData.value.contractId
				})
			)
			.then((res) => {
				res.forEach((it) => {
					it['name'] = it['material']['name']
					it['brand'] = it['material']['brand']
					it['spec'] = it['material']['spec']
					it['code'] = it['material']['code']
					it['unit'] = it['material']['unit']
					it['key'] = it['materialId']
				})
				return {
					records: res,
					total: res.length,
					current: 1,
					pages: 10
				}
			})
			.catch(() => {})
	}

	const selectorColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: 80,
			align: 'center'
		},
		{
			title: '商品编号',
			width: 100,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品名称',
			width: 120,
			dataIndex: 'name',
			align: 'center',
			ellipsis: true
		},
		{
			title: '品牌',
			width: 100,
			dataIndex: 'brand',
			align: 'center',
			ellipsis: true
		},
		{
			title: '规格',
			width: 100,
			dataIndex: 'spec',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品单价',
			width: 100,
			dataIndex: 'unitPrice',
			align: 'center',
			ellipsis: true
		}
	]

	const goodsColumns = [
		{
			title: '序号',
			width: 80,
			dataIndex: 'index',
			align: 'center'
		},
		{
			title: '商品编号',
			width: 120,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品名称',
			dataIndex: 'name',
			width: 180,
			align: 'center',
			ellipsis: true
		},
		{
			title: '单位',
			dataIndex: 'unit',
			width: 100,
			align: 'center'
		},
		{
			title: '规格型号',
			dataIndex: 'spec',
			width: 120,
			align: 'center'
		},
		{
			title: '采购价格',
			dataIndex: 'price',
			width: 120,
			align: 'center'
		},
		// {
		// 	title: '税率',
		// 	dataIndex: 'taxRate',
		// 	width: 120,
		// 	align: 'center'
		// },
		{
			title: '采购数量',
			dataIndex: 'orderNum',
			width: 120,
			align: 'center'
		},
		// {
		// 	title: '含税金额',
		// 	dataIndex: 'taxPrice',
		// 	width: 120,
		// 	align: 'center'
		// },
		// {
		// 	title: '不含税金额',
		// 	dataIndex: 'noTaxPrice',
		// 	width: 140,
		// 	align: 'center'
		// },
		{
			title: '交货日期',
			dataIndex: 'deliveryDate',
			width: 140,
			align: 'center'
		},
		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center'
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
